<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.trim="age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="save">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="list.splice(index, 1)">删除</button>
            <button @click="doEdit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        { name: "tome", age: 16, gender: "男" },
        { name: "jone", age: 15, gender: "女" },
      ],
      name: "",
      age: "",
      gender: "",
      // 用来标记是否为添加的变量
      isAdd: true,
      currentIdx: 0
    };
  },

  methods: {
    save() {
      // 如果这个变量为true就做新增
      // if (this.isAdd == true) {
      if (this.isAdd) {
        // 1. 非空判断
        if (this.name == "" || this.age == "" || this.gender == "")
          return alert("请输入完整的内容");

        // 2. 如果不为空，就把输入的内容加到数组里
        this.list.push({
          name: this.name,
          age: this.age,
          gender: this.gender,
        });
      } else {
        // 肯定是做修改
        this.list[this.currentIdx].name = this.name
        this.list[this.currentIdx].age = this.age
        this.list[this.currentIdx].gender = this.gender

        // 本次修改完了，就让下次默认点击又变添加
        this.isAdd = true
      }

      // 3. 清空输入的内容
      this.name = this.age = this.gender = "";
    },

    doEdit(index) {
      // 把点击拿到的下标存起来
      this.currentIdx = index
      // 根据下标取出对应的元素
      const obj = this.list[index];
      // 再把对象的属性显示到对应的输入框
      this.name = obj.name;
      this.age = obj.age;
      this.gender = obj.gender;

      // 把新增的标记改为false
      this.isAdd = false
    },
  },
};
</script>